package com.webmarmun.baza;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class BazasudskihvestakaitumacaActivity extends Activity {
	 Spinner spinner;
	String  chosenLang;
	int iCurrentSelection=0;
	static SitesList sitesList = MyXMLHandler.sitesList;
 
	/*
	 * start first asynctask that parses remote xml
	 */
	protected class InitTask extends AsyncTask<Void, Void, Void> {
		private final ProgressDialog mDialog = new ProgressDialog(
				BazasudskihvestakaitumacaActivity.this);
		
		protected Void doInBackground(Void... arg0) {	
			if(internetConnection() == true){
			parseIT();
			return null;
			}else{	
				return null;
			}
		}

		

		// -- gets called just before thread begins
		protected void onPreExecute() {
			super.onPreExecute();
			mDialog.setMessage(netInfo());
			mDialog.show();
			
		}

		// -- called from the publish progress
		protected void onProgressUpdate(Void[]... values) {
			// super.onProgressUpdate(values);

		}

		// -- called if the cancel button is pressed
		@Override
		protected void onCancelled() {
			super.onCancelled();
			// Log.i( "makemachine", "onCancelled()" );

		}

		// -- called as soon as doInBackground method completes
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			mDialog.dismiss();
			if(internetConnection() == true){
			showSpinner();
			}else{
				showErrorMessage();
			}
		}

	}

	/*
	 * end asynctask1
	 */
	
	
	
	
	
	
	
	
	
	
	
	/*
	 * Shows error message if there is no internet connection
	 * 
	 */
	public void showErrorMessage(){
		
		new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Судски тумач")
        .setMessage("Нема везе ка интернету !!!")
        .setPositiveButton("У реду", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                //Stop the activity
            	BazasudskihvestakaitumacaActivity.this.finish();    
            }

        })
       
        .show();
	}
	
	
	/*
	 * Parsing remote xml document
	 * 
	 */
	public void parseIT() {

		try {

			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL(
					"http://prvisud.rs/magicxml/baza_tumaca.xml");

			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			MyXMLHandler myXMLHandler = new MyXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));
			sitesList = MyXMLHandler.sitesList;
			

		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}

	}
   
	
	/*
	 * Starts Secon asynctask and passes language string as parameter
	 * 
	 */
	public void showIT(String lang) {
		Bundle bundle = new Bundle();
		bundle.putString("param", lang);
		Intent in = new Intent(BazasudskihvestakaitumacaActivity.this,SingleView.class);
		in.putExtras(bundle);
		BazasudskihvestakaitumacaActivity.this.startActivityForResult(in,0);
		
	}
	
	
	
	
    /*
     * On Create
     */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		 //setTheme(R.style.Theme_Translucent);
		new InitTask().execute();
		// ImageView image = (ImageView) findViewById(R.id.image);
		if(internetConnection() == true){
			setContentView(R.layout.main);
		LayoutInflater inflater = getLayoutInflater();
		View layout1 = inflater.inflate(R.layout.toast_layout,
				(ViewGroup) findViewById(R.id.toast_layout_root));

		ImageView image2 = (ImageView) layout1.findViewById(R.id.image_toast);
		image2.setImageResource(R.drawable.image);
		TextView text = (TextView) layout1.findViewById(R.id.text);
		text.setText("Притиском на MENU дугме можете изабрати неку од опција за претрагу базе судских тумача");

		Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
		toast.setDuration(Toast.LENGTH_LONG);

		toast.setView(layout1);
		toast.show();
		}
		
	}
	
	
	
    /*
     * 
     * (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu, menu);
		return true;
	}
	
	
	/*
	 * 
	 * (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.search:
	            //newGame();
	        
	            return true;
	        case R.id.mail:
	            //showHelp();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	
	/*
	 * Shows spinner and adds onItemSelected action to spinner
	 * 
	 */
	
	public void showSpinner(){
		 spinner = (Spinner) findViewById(R.id.spinner);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.jezici, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	    iCurrentSelection = spinner.getSelectedItemPosition();
		  spinner.setOnItemSelectedListener(new OnItemSelectedListener()
	        {

	            @Override
	            public void onItemSelected(AdapterView<?> arg0, View arg1,
	                    int arg2, long arg3) {
	                // TODO Auto-generated method stub
	                switch (arg2) {
	                case 0:                    
	                    break;

	                case 1:                 
	                	
	                	showIT(spinnerGetLang());
	                    break;
	                    
	                case 2:                 
	                	showIT(spinnerGetLang());                 
	                    break;
	                case 3:                 
	                	showIT(spinnerGetLang());                    
	                    break;
	                    
	                case 4:                 
	                	showIT(spinnerGetLang());                   
	                    break;
                   
	                case 5:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 6:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 7:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 8:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 9:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 10:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 11:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 12:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 13:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 14:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 15:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 16:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 17:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 18:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 19:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 20:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 21:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 22:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 23:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 24:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 25:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 26:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 27:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 28:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 29:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 30:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 31:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 32:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                case 33:                 
	                	showIT(spinnerGetLang());                   
	                    break;
	                default :                       
	                    break;
	                }
	            }

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
	        });

	}
	
	
	
	
	    /*
	     * get selected language from spinner
	     */
		private String spinnerGetLang() {
			
			chosenLang = spinner.getSelectedItem().toString();
			return chosenLang;
			
		}
		
		
		
		/*
		 * determins if there is internet connection
		 * 
		 */
		public boolean internetConnection() {
	        ConnectivityManager connMgr=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo info=connMgr.getActiveNetworkInfo();
	        
	       

	        return(info!=null && info.isConnected());

	} 
		
		
		
		
		/*
		 * Determining weather there is internet connection and returns string that shows state
		 * 
		 */
		public String netInfo(){
			String response;
			String status="";
			 ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			
	            NetworkInfo netInfo = conMan.getActiveNetworkInfo();
	            if(netInfo == null){
	            	response = "Нема интернет конекције";
	            }else{
	             status= netInfo.getState().toString();
	            }

		    	  if (status.equals("CONNECTED")) {
		    		  response = "Учитавање података о судским тумачима";
		            } else {
		            	response = "Нема интернет конекције";
		            }

		    	  return response;
			
		}
		
		
		
		
     

	
	


}